package com.personalsystem.account.action;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.personalsystem.account.bean.Account;
import com.personalsystem.account.dao.AccountDao;
import com.personalsystem.account.service.AccountService;
import com.personalsystem.role.bean.Role;
import com.personalsystem.role.dao.RoleDao;
import com.personalsystem.role.util.RoleUtil;
import com.personalsystem.tool.BackJson;
import com.personalsystem.tool.encryption.EncrypDES;
import com.personalsystem.tool.hibernate.Updater;
import com.personalsystem.tool.hibernate.Updater.UpdateMode;
import com.personalsystem.tool.page.Page;


/**
 * 帐号管理
 * @author bruce
 *
 */
@Controller
public class AccountAction {
	
	@Autowired
	@Qualifier("accountService")
	private AccountService service;
	
	@Autowired
	@Qualifier("accountDao")
	private AccountDao dao;
	
	@Autowired
	@Qualifier("roleDao")
	private RoleDao roleDao;
	
	@RequestMapping("/account/loadRoleAll.do")
	public void loadRoleAll(HttpServletRequest request,HttpServletResponse response){
		List<Role> list=roleDao.findByProperty("status", 1);
		JSONArray array=new JSONArray();
		for(Role role:list){
			JSONObject object=new JSONObject();
			object.put("boxLabel", role.getName());
			object.put("inputValue", role.getId());
			object.put("name", "role");
			array.add(object);
		}
		String resultString=array.toString();
		BackJson.backJsonToHTML(response, resultString);
	}
	
	@RequestMapping("/account/loadTable.do")
	public void loadAccountTable(int start,int limit,HttpServletRequest request,HttpServletResponse response){
		Page page=dao.getPage(start+1, limit);
		String jsonString=new RoleUtil().getTableJson(page);
		System.out.println(jsonString);
		BackJson.backJsonToHTML(response, jsonString);
	}
	
	@RequestMapping("/account/addAccount.do")
	public void addAccount(Account account,String roleIdx,HttpServletRequest request,HttpServletResponse response){
		String[] strings=roleIdx.split(",");
		Set<Role> set=new HashSet<Role>();
		for(String s:strings){
			if(!s.equals("")){
				Role role=roleDao.get(Long.parseLong(s));
				set.add(role);
			}
		}
		try{
			if(!account.getPassword().trim().equals("")){
				 EncrypDES de1 = new EncrypDES();  
			     byte[] encontent = de1.Encrytor(account.getPassword());
			     account.setPassword(new String(encontent));
			}else{
				if(account.getId()!=null){
					account.setPassword(null);
				}
			}
		}catch (Exception e) {
			// TODO: handle exception
		}
		account.setRoleSet(set);
		account.setRemark(Jsoup.parse(account.getRemarkUbb()).text());
		if(account.getId()==null){
			account.setStatus(1);
			service.save(account);
		}else{
			Updater<Account> updater=new Updater<Account>(account,UpdateMode.MIDDLE);
			service.updateByUpdater(updater);
		}
		
		BackJson.backJsonToHTML(response, "{success:true,msg:'保存成功'}");
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/account/loadAccount.do")
	public void loadAccount(long id,HttpServletRequest request,HttpServletResponse response){
		Account account=service.findById(id);
		Map map=new TreeMap();
		map.put("success", true);
		map.put("data", account);
		JSONObject object=new JSONObject();
		object.putAll(map);
		BackJson.backJsonToHTML(response, object.toString());
	}
	
	@RequestMapping("/account/loadRoleByAccountId.do")
	public void loadRoleByAccountId(long id,HttpServletRequest request,HttpServletResponse response){
		Account account=service.findById(id);
		Set<Role> set=account.getRoleSet();
		List<Role> list=roleDao.findByProperty("status", 1);
		JSONArray array=new JSONArray();
		for(Role role:list){
			JSONObject object=new JSONObject();
			object.put("boxLabel", role.getName());
			object.put("inputValue", role.getId());
			object.put("name", "role");
			if(set.contains(role)){
				object.put("checked", true);
			}
			array.add(object);
		}
		String resultString=array.toString();
		BackJson.backJsonToHTML(response, resultString);
	}
	
	
	@RequestMapping("/account/deleteAccount.do")
	public void deleteAccount(String idx,HttpServletRequest request,HttpServletResponse response){
		String[] arr=idx.split(",");
		List<Long> list=new ArrayList<Long>();
		for(String s:arr){
			if(!s.equals("")){
				list.add(Long.parseLong(s));
			}
		}
		Long[] lArr=new Long[list.size()];
		for(int i=0;i<list.size();i++){
			lArr[i]=list.get(i);
		}
		service.deleteById(lArr);
		BackJson.backJsonToHTML(response, "{success:true,msg:'保存成功'}");
	}

}
